package checkers3d.storage;



import java.io.*;
import java.util.*;
import checkers3d.logic.*;

/**
 *
 * @author Sean
 */
public class DataManagerStats {



// create indiviual statistic
    public static void createIndividualStatistic(Player player) throws IOException{
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);//write ststs file
        BufferedWriter out = new BufferedWriter(fw);
int wins=0;
int losses=0;
int ties=0;
       

        out.write(player.getName() + "\t" + wins + "\t" + losses + "\t" + ties);//stat line
        out.newLine();
        out.close();
    }
//update stats
    public static void updateInidivualStatistic(Player playerAccount, boolean wins, boolean losses, boolean ties) throws IOException{
        createBackupStatisticsFile();// create back up file
        deleteStatistics();// delete existing stat

        String tempName = new String();
        int winsToUpdate = 0;
        int lossesToUpdate = 0;
        int tiesToUpdate = 0;

        // Open BackupStatistics.txt file for reading
        FileReader fr = new FileReader("BackupStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open PlayerStatistics.txt file for writing
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);

        while (scan.hasNext()){
            tempName = scan.next();

            // If the player's name if found in the statistics file,
            // update the wins, losses, and ties accordingly.
            if (tempName.equals(playerAccount.getName())){//if name is player name
                if (wins == true)
                    winsToUpdate = scan.nextInt() + 1;//increment 1 if it's a wining
                else if (wins == false)
                    winsToUpdate = scan.nextInt();//don't increment 1 if it's not a win
                if (losses == true)
                    lossesToUpdate = scan.nextInt() + 1;//increment 1 if it's a losinng
                else if (losses == false)//don't increment 1 if it's not a lose
                    lossesToUpdate = scan.nextInt();
                if (ties == true)//increment 1 if it's a tie
                    tiesToUpdate = scan.nextInt() + 1;
                else if (ties == false)//don't increment 1 if it's not a tie
                    tiesToUpdate = scan.nextInt();

                String buildStatistic = new String(tempName + "\t"
                        + winsToUpdate + "\t"
                        + lossesToUpdate + "\t"
                        + tiesToUpdate);

                out.write(buildStatistic);// write new stats
                out.newLine();
            }
            // If name isn't found, write the name and password to the
            // PlayerStatistics.txt file.
            else{
                String buildStatistic = new String(tempName + "\t"
                        + scan.nextInt() + "\t"
                        + scan.nextInt() + "\t"
                        + scan.nextInt());
                out.write(buildStatistic);
                out.newLine();
            }
        }

        out.newLine();
        out.close();
    }
    // add the stats vs an opponent

    public static void addOpponentStats(Player playerOne, Player playerTwo,int wins ,int losses, int ties) throws IOException{


       String name1= playerOne.getName();
       String name2=playerTwo.getName();

      String  playerStats1 = (name1+"/vs./"+name2+ "\t" + wins + "\t" + losses + "\t" + ties);// write stats vs opponent
     String playerStats2 = (name2+"/vs./"+name1+ "\t" + losses + "\t" + wins + "\t" + ties);// write stats vs opponent

        createBackupStatisticsFile();
        deleteStatistics();
           // Open BackupStatistics.txt file for reading
        FileReader fr = new FileReader("BackupStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open PlayerStatistics.txt file for writing
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);
     // System.out.print(name1);
            //System.out.print(name2);
 while (scan.hasNextLine()){//while reading backup file
            String line=scan.nextLine();
           
            StringTokenizer st = new StringTokenizer(line, "\t");
            String token=st.nextToken();
            
           

            if (token.equals(name1)){// if it reads stats for player1
            
            out.write(line);// print stats
            out.newLine();
            out.write(playerStats1);
            out.newLine();
      }//print stats vs oponent
            else if(token.equals(name2)){// same for player2
           
            out.write(line);
            out.newLine();
            out.write(playerStats2);
            out.newLine();}
            else// print players stats for others
            {
            //System.out.println(line);
            out.write(line);
            out.newLine();
            }

 }
      out.close();
      scan.close();
       }

    //checks if oponent Stats exist
public static boolean isOpponentStatsExist(Player player1,Player player2) throws FileNotFoundException
{       boolean flag=false;
        FileReader fr = new FileReader("PlayerStatistics.txt");
        Scanner scan = new Scanner(fr);

        String name1=player1.getName();
        String name2=player2.getName();


        while (scan.hasNextLine()){
            String line = scan.nextLine();
            StringTokenizer st = new StringTokenizer(line, "\t");
            if (line.contains("vs.") && st.nextToken().equals(name1+"/vs./"+name2)){//if it starts with palyer1vsplayer2
                flag = true;
               //take first value
                break;
            }

        }

        scan.close();

return flag;
}
        

    public static void updateOponentStats(Player player1, Player player2,boolean wins, boolean losses, boolean ties) throws IOException
    {
        //add the stats for the opponent if they do not already exist.
        if(!isOpponentStatsExist(player1, player2))
            addOpponentStats(player1, player2, 0, 0, 0);

        createBackupStatisticsFile();// create back up file
        deleteStatistics();// delete existing stat

        String tempName = new String();
        int winsToUpdate = 0;
        int lossesToUpdate = 0;
        int tiesToUpdate = 0;

        // Open BackupStatistics.txt file for reading
        FileReader fr = new FileReader("BackupStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open PlayerStatistics.txt file for writing
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);

        while (scan.hasNext()){
            tempName = scan.next();

            // If the player's name if found in the statistics file,
            // update the wins, losses, and ties accordingly.
            if (tempName.equals(player1.getName()+"/vs./"+player2.getName())){//if name is player name
                if (wins == true)
                    winsToUpdate = scan.nextInt() + 1;//increment 1 if it's a wining
                else if (wins == false)
                    winsToUpdate = scan.nextInt();//don't increment 1 if it's not a win
                if (losses == true)
                    lossesToUpdate = scan.nextInt() + 1;//increment 1 if it's a losinng
                else if (losses == false)//don't increment 1 if it's not a lose
                    lossesToUpdate = scan.nextInt();
                if (ties == true)//increment 1 if it's a tie
                    tiesToUpdate = scan.nextInt() + 1;
                else if (ties == false)//don't increment 1 if it's not a tie
                    tiesToUpdate = scan.nextInt();

                String buildStatistic = new String(tempName + "\t"
                        + winsToUpdate + "\t"
                        + lossesToUpdate + "\t"
                        + tiesToUpdate);

                out.write(buildStatistic);// write new stats
                out.newLine();
            }
            // If name isn't found, write the name and password to the
            // PlayerStatistics.txt file.
            else{
                String buildStatistic = new String(tempName + "\t"
                        + scan.nextInt() + "\t"
                        + scan.nextInt() + "\t"
                        + scan.nextInt());
                out.write(buildStatistic);
                out.newLine();
            }
        }

        out.newLine();
        out.close();
    }
    /**
     * Deletes the entire statistics file.
     */
    public static void deleteStatistics() throws IOException{
        FileWriter fw = new FileWriter("PlayerStatistics.txt", false);
        fw.close();
    }

    /**
     * Deletes the entire backup statistics file.
     */
    public static void deleteBackupStatistics() throws IOException{
        FileWriter fw = new FileWriter("BackupStatistics.txt", false);
        fw.close();
    }

    /**
     * Creates a backup of the statistics file.
     */
    public static void createBackupStatisticsFile() throws IOException{
        deleteBackupStatistics();

        // Open the Accounts.txt file for reading only.
        FileReader fr = new FileReader("PlayerStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open the BackupAccounts.txt file for appending.
        FileWriter fw = new FileWriter("BackupStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);

        // Copy the each line from the Accounts.txt file to the
        // BackupAccounts.txt file.
        while (scan.hasNext()){
            out.write(scan.nextLine());
            out.newLine();
        }

        scan.close();
        out.close();
    }
    public static void removePlayerStats(Player player1) throws FileNotFoundException, IOException
{        
       if (DataManagerAccounts.doesPlayerExist(player1.getName())){//check existance of player to remove
        createBackupStatisticsFile();
         deleteStatistics();
         // Open BackupStatistics.txt file for reading

        FileReader fr = new FileReader("BackupStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open PlayerStatistics.txt file for writing
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);
       
 while (scan.hasNext()){//read from Backup file
     String line=scan.nextLine();
     StringTokenizer st1 = new StringTokenizer(line, "\t");
     String stn1=st1.nextToken();
             if (!stn1.equals(player1.getName())){//if name not found write back in the file
                 //if found don't write anything
                out.write(line);
                out.newLine();
             }
 }
    scan.close();
         out.close(); }
       
    }
    //get win value
      public static String getWins(Player player) throws FileNotFoundException
    {  
       if (DataManagerAccounts.doesPlayerExist(player.getName())){//check existence
          FileReader fr = new FileReader("PlayerStatistics.txt");
        Scanner scan1 = new Scanner(fr);

        boolean flag = false;
        String win = new String();

        while (scan1.hasNextLine()){
            StringTokenizer st = new StringTokenizer(scan1.nextLine(), "\t");
            if (st.nextToken().equals(player.getName())){// if it starts with player name
                flag = true;
                win = st.nextToken();//get next token
                break;
            }
        }

        return win;}
       else{
            return "error";// if player not found return error
       }
    }
      //set win value
    public static void setWins(int wins,Player player) throws FileNotFoundException, IOException
    {
       if (DataManagerAccounts.doesPlayerExist(player.getName())){

        String loss= getLosses(player);//get loss and tie value
        String tie= getTies(player);

        createBackupStatisticsFile();
        deleteStatistics();
         // Open BackupStatistics.txt file for reading

        FileReader fr = new FileReader("BackupStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open PlayerStatistics.txt file for writing
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);


        while (scan.hasNextLine()){
            String line=scan.nextLine();
            
            StringTokenizer st = new StringTokenizer(line, "\t");
            if (!(st.nextToken().equals(player.getName()))){// if not starting with player name
                out.write(line);
                out.newLine();//print stats
            }
            else
            {//print new stats with new win value
               out.write(player.getName() + "\t" + wins + "\t" + loss + "\t" + tie);
               out.newLine();
            }
       
        }
         scan.close();
        out.close();
       }


    }
    //get loss value
    public static String getLosses(Player player) throws FileNotFoundException
    {   
       if (DataManagerAccounts.doesPlayerExist(player.getName())){
        FileReader fr = new FileReader("PlayerStatistics.txt");
        Scanner scan1 = new Scanner(fr);

        boolean flag = false;
        String loss = new String();

        while (scan1.hasNextLine()){
            StringTokenizer st = new StringTokenizer(scan1.nextLine(), "\t");
            if (st.nextToken().equals(player.getName())){
                flag = true;
                st.nextToken();
                loss=st.nextToken();//take second value

                break;
            }
        }

       
        return loss;}
       else{
             return "error";
       }
    }
    //set loss value
    public static void setLosses(Player player,int losses) throws IOException
    {   
       if (DataManagerAccounts.doesPlayerExist(player.getName())){

        String tie= getTies(player);
        String win= getWins(player);

        createBackupStatisticsFile();
         deleteStatistics();
         // Open BackupStatistics.txt file for reading

        FileReader fr = new FileReader("BackupStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open PlayerStatistics.txt file for writing
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);


        while (scan.hasNextLine()){
             String line = scan.nextLine();
            StringTokenizer st = new StringTokenizer(line, "\t");
            if (!(st.nextToken().equals(player.getName()))){
                out.write(line);
                out.newLine();
            }
            else
            {
               out.write(player.getName() + "\t" + win + "\t" + losses + "\t" + tie);
               out.newLine();
            }
        
        }
        scan.close();
        out.close();
       }


    }
    //get ties
    public static String getTies(Player player) throws FileNotFoundException
    {
       if (DataManagerAccounts.doesPlayerExist(player.getName())){
           FileReader fr = new FileReader("PlayerStatistics.txt");
        Scanner scan1 = new Scanner(fr);

        boolean flag = false;
        String tie = new String();

        while (scan1.hasNextLine()){
            StringTokenizer st = new StringTokenizer(scan1.nextLine(), "\t");
            if (st.nextToken().equals(player.getName())){
                flag = true;
                st.nextToken();
                st.nextToken();
                tie=st.nextToken();//take third value
                break;
            }
        }

       
        return tie;
    }
       else{
          return "error";
       }
       }
//set ties
    public static void setTies(Player player,int ties) throws FileNotFoundException, IOException
    { 
       if (DataManagerAccounts.doesPlayerExist(player.getName())){

        String loss= getLosses(player);
        String win= getWins(player);

        createBackupStatisticsFile();
         deleteStatistics();
         // Open BackupStatistics.txt file for reading

        FileReader fr = new FileReader("BackupStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open PlayerStatistics.txt file for writing
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);


        while (scan.hasNext()){
            String line = scan.nextLine();
           
            StringTokenizer st = new StringTokenizer(line, "\t");
            if (!(st.nextToken().equals(player.getName()))){
                out.write(line);
                out.newLine();
            }
            else
            {
               out.write(player.getName() +"\t" + win + "\t" + loss + "\t" + ties);
               out.newLine();
            }
        
        }
        scan.close();
        out.close();
       }

    }
    //get wins against opponent
    public static String getPlayerWins(String name,String name2) throws FileNotFoundException{
        FileReader fr = new FileReader("PlayerStatistics.txt");
        Scanner scan = new Scanner(fr);

        boolean flag = false;
        String win = new String();

        while (scan.hasNextLine()){
            StringTokenizer st = new StringTokenizer(scan.nextLine(), "\t");
            if (st.nextToken().equals(name+"/vs./"+name2)){//if it starts with palyer1vsplayer2
                flag = true;
                win = st.nextToken();//take first value
                break;
            }
        }

        scan.close();
        return win;
    }
     public static String getPlayerLosses(String name,String name2) throws FileNotFoundException{
        FileReader fr = new FileReader("PlayerStatistics.txt");
        Scanner scan = new Scanner(fr);

        boolean flag = false;
        String loss = new String();

        while (scan.hasNextLine()){
            StringTokenizer st = new StringTokenizer(scan.nextLine(), "\t");
            if (st.nextToken().equals(name+"/vs./"+name2)){
                flag = true;
                st.nextToken();
                loss=st.nextToken();

                break;
            }
        }

        scan.close();
        return loss;
    }
   public static String getPlayerTies(String name,String name2) throws FileNotFoundException{
        FileReader fr = new FileReader("PlayerStatistics.txt");
        Scanner scan = new Scanner(fr);

        boolean flag = false;
        String tie = new String();

        while (scan.hasNextLine()){
            StringTokenizer st = new StringTokenizer(scan.nextLine(), "\t");
            if (st.nextToken().equals(name+"/vs./"+name2)){
                flag = true;
                st.nextToken();
                st.nextToken();
                tie=st.nextToken();
                break;
            }
        }

        scan.close();
        return tie;
    }

public static void removeOponentStats(Player player1,Player player2) throws FileNotFoundException, IOException
{      
         createBackupStatisticsFile();
         deleteStatistics();
         // Open BackupStatistics.txt file for reading

      FileReader fr = new FileReader("BackupStatistics.txt");
        Scanner scan = new Scanner(fr);
        // Open PlayerStatistics.txt file for writing
        FileWriter fw = new FileWriter("PlayerStatistics.txt", true);
        BufferedWriter out = new BufferedWriter(fw);
      

 while (scan.hasNext()){
   String line=scan.nextLine();
     StringTokenizer st1 = new StringTokenizer(line, "\t");
     String stn1=st1.nextToken();
    
     String name1=player1.getName();
     String name2=player2.getName();

             if (!(stn1.equals(name1+"/vs./"+name2))){
             if (!(stn1.equals(name2+"/vs./"+name1))){
                out.write(line);//write next line if it doesn't start with player1 vs player2 or player2 vs player1
            out.newLine();
             }
             }
            


 } scan.close();
         out.close();
    }
           

    public static void setOpponentStats(Player player1,Player player2,int wins, int losses, int ties) throws FileNotFoundException, IOException
    {
        //if the versus already exists, delete it.
        if(isOpponentStatsExist(player1,player2))
            removeOponentStats(player1,player2);//remove then add new stats
        
        //add the new versus stats
        addOpponentStats(player1,player2,wins,losses, ties);
    }
}